package com.xxbb.springbootapi.service.impl;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.xxbb.springbootapi.entity.SiteOperator;
import com.xxbb.springbootapi.service.ISiteOperatorService;
import com.xxbb.springbootapi.util.jwt.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;


@Service
public class SiteOperatorService implements ISiteOperatorService {
    @Autowired
    HttpServletRequest request;

    public SiteOperator getOperator() {
        SiteOperator siteOperator = new SiteOperator();
        String token = null;
        //获取token
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            //从cookie中获取
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals("Authorization")) {
                    token = cookie.getValue();
                }
            }
        } else {
            //从请求头中获取
            token= request.getHeader("Authorization");
        }
        //获取基本信息
        DecodedJWT jwt = JwtUtil.verifyToken(token);
        siteOperator.setToken(token);
        siteOperator.setName(jwt.getClaim("name").asString());
        siteOperator.setId(Integer.parseInt(jwt.getClaim("id").asString()));
        siteOperator.setUserId(Integer.parseInt(jwt.getClaim("userId").asString()));
        siteOperator.setAuthority(jwt.getClaim("account").asString());
        return siteOperator;
    }
}
